package com.wenlin.userservice.controller;


import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.wenlin.userservice.exception.*;
import com.wenlin.userservice.response.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Tech-606
 * 统一异常处理
 */
@ControllerAdvice
@ResponseBody
public class ErrorHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(Exception.class)
    public Message processValidationError(Exception e, HttpServletRequest request) {

      Message rest = new Message();

        if (e instanceof IllegalArgumentException) {
            rest.setCode(2);
            rest.setMsg(e.getMessage());
        } else if (e instanceof NotFoundException) {
            rest.setCode(ErrorCode.LIMIT_RATE.value());
            rest.setMsg(e.getMessage());
        } else if (e instanceof NotFoundSiteInfoException) {
          rest.setCode(ErrorCode.LIMIT_SITE.value());
          rest.setMsg(e.getMessage());
        } else if(e instanceof  IllegalMonitorStateException){
            rest.setCode(ErrorCode.LIMIT_SITE.value());
            rest.setMsg("锁已超时或者不是当前线程解锁，请稍后再试");
        }else if(e instanceof TryLockTimeOutException){
            rest.setCode(ErrorCode.LIMIT_SITE.value());
            rest.setMsg("请求锁超时");
        }
        else {
            rest.setCode(ErrorCode.SERVER_BUSY.value());
            rest.setMsg(e.getMessage());
        }

        logger.error("OH,MY GOD! SOME ERRORS OCCURED! AS FOLLOWS :{}"+e.getMessage());

        return rest;
    }
    @ExceptionHandler(value=MethodArgumentNotValidException.class)
    public Message methodArgumentNotValidHandler(HttpServletRequest request,
                                                MethodArgumentNotValidException exception) throws Exception
    {
        //按需重新封装需要返回的错误信息
        List<ArgumentInvalidResult> invalidArguments = new ArrayList<>();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            ArgumentInvalidResult invalidArgument = new ArgumentInvalidResult();
            invalidArgument.setDefaultMessage(error.getDefaultMessage());
            invalidArgument.setField(error.getField());
            invalidArgument.setRejectedValue(error.getRejectedValue());
            invalidArguments.add(invalidArgument);
        }
        logger.error("OH,MY GOD! SOME ERRORS OCCURED! AS FOLLOWS :{}",exception.getMessage());
      Message rest = new Message();
        rest.setCode(ErrorCode.ILLEGAL_ARGUMENT.value());
        rest.setMsg(ErrorCode.ILLEGAL_ARGUMENT.getReasonPhrase());
        rest.setData(invalidArguments);
        return rest;
    }
}
